/**
 *Copyright (c) 2024 watereyes
 * workflow is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.workflow.api.listener;

import java.util.List;

import org.activiti.engine.EngineServices;
import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.event.ActivitiEvent;
import org.activiti.engine.task.Task;
import org.koron.ebs.mybatis.ADOConnection;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.SqlTask;

import com.koron.workflow.api.bean.HistoryBillsBean;
import com.koron.workflow.api.bean.SubHistoryBillsBean;
import com.koron.workflow.api.mapper.HistoryBillsMapper;
import com.koron.workflow.api.mapper.SubHistoryBillsMapper;
import com.koron.workflow.api.mapper.TaskListMapper;

/**
 * 流程挂起
 * 将任务列表里当前流程状态置为挂起状态
 * @author bin
 *
 */
public class ProcessSuspendListener extends ProcessListenerAdapter{
	
	@Override
	public void processSuspend(ActivitiEvent event) {
		EngineServices engineServices = event.getEngineServices();
		TaskService taskService = engineServices.getTaskService();
		List<Task> tasks = taskService.createTaskQuery().processInstanceId(event.getProcessInstanceId()).list();
		ADOConnection.runTask(new SqlTask() {
			@Override
			public Void run(SessionFactory factory) {
				//将任务列表的状态修改为已挂起
				for(Task task : tasks) {
					factory.getMapper(TaskListMapper.class).updateStatus(task.getId(), 3);
				}
				SubHistoryBillsMapper mapper = factory.getMapper(SubHistoryBillsMapper.class);
				SubHistoryBillsBean subBill = mapper.findByProcessInstanceId(event.getProcessInstanceId());
				if(subBill != null) {
					mapper.updateStatusByProcessInstanceId(event.getProcessInstanceId(), 3);
				}else {
					HistoryBillsMapper billMapper = factory.getMapper(HistoryBillsMapper.class);
					HistoryBillsBean bill = billMapper.findByProcessInstanceId(event.getProcessInstanceId());
					billMapper.updateStatus(bill.getBillId(), 3);
				}
				return null;
			}
		}, Void.class);
	}
}
